package com.auto.printer.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import com.auto.printer.common.entity.BaseColumn;
import com.auto.printer.entity.po.PrinterTask;
import com.auto.printer.enums.PrintTaskStatusEnum;
import com.auto.printer.properties.PrinterProperties;
import com.auto.printer.service.PrinterTaskService;
import com.auto.printer.utils.Printer;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;

/**
 * @author LoveHuaHua
 * @date 2023年08月14日 21:38
 * @description believe in yourself
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class StaticSchedule {

    public final PrinterProperties printerProperties;
    private final PrinterTaskService printerTaskService;

    @Scheduled(fixedDelay = 10 * 1000)
    public void runPrint() throws Exception {
        if (CollUtil.isEmpty(printerProperties.getDeviceList())) {
            return;
        }
        PrinterTask one = printerTaskService.lambdaQuery().orderByAsc(BaseColumn::getCreateTime).eq(PrinterTask::getTaskStatus, PrintTaskStatusEnum.QUEUE.getCode()).in(PrinterTask::getPrinterNo, printerProperties.getDeviceList()).last("LIMIT 1").one();
        if (one != null) {
            one.setStartTime(LocalDateTime.now());
            one.setTaskStatus(PrintTaskStatusEnum.ING.getCode());
            printerTaskService.updateById(one);

            try {
                File downloaded = HttpUtil.downloadFileFromUrl(one.getFilePath(), "download/" + UUID.fastUUID() + "/" + FileUtil.getName(one.getFilePath()));
                Printer.handlerFileDoc(downloaded, one.getPrinterNo(), one.getSideFlag(), one.getColorFlag());
                Printer.waitDevicePrint(one.getPrinterNo());
            } catch (Exception e) {
                one.setErrorMessage(e.getMessage());
                one.setTaskStatus(PrintTaskStatusEnum.FAIL.getCode());
                printerTaskService.updateById(one);
                throw e;
            }
            one.setTaskStatus(PrintTaskStatusEnum.SUCCESS.getCode());
            one.setEndTime(LocalDateTime.now());
            printerTaskService.updateById(one);

        }
    }

}
